﻿using System;
using SystemX.Infrastructure;
using Csla.Server.Hosts.Silverlight;
using SystemX.Services;

namespace SystemX.Csla
{
    /// <summary>
    /// A WcfPortal with compression utility
    /// </summary>
    public class CompressedWcfPortal:WcfPortal
    {
        private ICompresser compresser;
        #region .ctor
        /// <summary>
        /// .ctor with specified ICompresser instance
        /// </summary>
        /// <param name="_compresser"></param>
        public CompressedWcfPortal(ICompresser _compresser) {
            compresser = _compresser;
        }
        /// <summary>
        /// default .ctor
        /// </summary>
        public CompressedWcfPortal():this(ServiceLocatorX<ICompresser>.GetService()) { }
        #endregion

        protected override CriteriaRequest ConvertRequest(CriteriaRequest request)
        {
            CriteriaRequest returnValue = new CriteriaRequest {
                ClientContext = compresser.Decompress(request.ClientContext),
                GlobalContext = compresser.Decompress(request.GlobalContext) 
            };
            if (request.CriteriaData != null)
                returnValue.CriteriaData = compresser.Decompress(request.CriteriaData);
            returnValue.Principal = compresser.Decompress(request.Principal);
            returnValue.TypeName = request.TypeName;
            return returnValue;
        }

        protected override UpdateRequest ConvertRequest(UpdateRequest request)
        {
            UpdateRequest returnValue = new UpdateRequest {
                ClientContext = compresser.Decompress(request.ClientContext),
                GlobalContext = compresser.Decompress(request.GlobalContext),
                ObjectData = compresser.Decompress(request.ObjectData),
                Principal = compresser.Decompress(request.Principal) 
            };
            return returnValue;
        }

        protected override WcfResponse ConvertResponse(WcfResponse response)
        {
            WcfResponse returnValue = new WcfResponse {
                GlobalContext = compresser.Compress(response.GlobalContext),
                ObjectData = compresser.Compress(response.ObjectData), 
                ErrorData = response.ErrorData
            };
            return returnValue;
        }
    }
}
